--
-- Author: gnar
-- Date: 2014-12-01 17:25:06
--
local ChatLayer = class("ChatLayer", function() return CCNode:create() end)
local topChatNodeTag = 10001

function ChatLayer:ctor(chatType)

    self:_initData(chatType)
    self:_init()

end
--------------------------------------------
function ChatLayer:_initData(chatType)

    self._needInitDisplay = true
    self._needInitListener = true
    self._needInitWithData = true

    self._topSysChatLableHeight = nil
    self._scrollOffsetYs = {0,0,0,0}

    self._displayingChatType = chatType or 1
    self._displayingPersonUid = nil
    self._displayingChatList = ChatSystem:getChatListByType(self._displayingChatType)  
    self._displayingLabelHeightList = ChatSystem:getChatLableHeightLists(self._displayingChatType) 


    self.tableViewTouchEnableList = {false,false,false,false}

end

function ChatLayer:_init()

    self:addNodeEventListener(cc.NODE_EVENT, handler(self, self._onNodeEvent))
    self:_updateDisplayWithData()

end

function ChatLayer:_onNodeEvent(event)

    if event.name == "enter" then
        NotificationManager:registerObserver(ENUM_CHAT_EVENT_NAME.NEW_CHAT,self,handler(self,self.onReceiveNewChat) )
    elseif event.name == "exit" then
        NotificationManager:unregisterObserver(ENUM_CHAT_EVENT_NAME.NEW_CHAT,self)
    elseif event.name == "cleanup" then
        
    end

end

function ChatLayer:_updateDisplayWithData()
   
    self:_initDisplay()
    self:_initListener()
    self:_initWithData()

    self:_updateChatContentBoxWithData()

end

function ChatLayer:_initWithData()

    if self._needInitWithData then
        self._needInitWithData = false

        self:_initTopBtn()
    end

end

function ChatLayer:_initTopBtn()
    
    self:_updateTopBtnDisplay(self._displayingChatType)

end


function ChatLayer:_initDisplay()

    if self._needInitDisplay then
        self._needInitDisplay = false

        self.mMainView = CCBLayer:load(PathManager:getMainCCBIFile("ChatLayer"), "ChatLayer")
        tolua.cast(self.mMainView, "CCLayer"):addTo(self) 

        self:_readCcbi()
        --editbox
        local edixBoxSize = CCSizeMake(self.editBoxBar:getContentSize().width-30, 40)
        self.editBox  = ui.newEditBox({image = CCScale9Sprite:create(),listener = handler(self, self._onEditBox),size = edixBoxSize})

        self.editBox:setPlaceHolder(WordManager:getWord("ChatLayer_004"))
        self.editBox:setAnchorPoint(CCPoint(0, 0.5))
        self.editBox:setFontSize(30)
        self.editBox:setFontColor(text.color2)
        self.editBox:setPlaceholderFontColor(text.color2)
        self.editBox:setPlaceholderFontSize(22)
        self.editBox:setReturnType(kKeyboardReturnTypeDone)
        self.editBox:setInputMode(kEditBoxInputModeSingleLine)
        self.editBox:setPosition(15, self.editBoxBar:getContentSize().height / 2)
        self.editBox:addTo(self.editBoxBar )


        self.tableView       = CCTableView:create(CCSizeMake(0,0))
        
        self.tableView:setTouchEnabled(self.tableViewTouchEnableList[self._displayingChatType])

        self.tableView :setDirection(kCCScrollViewDirectionVertical)
        self.tableView :setVerticalFillOrder(kCCTableViewFillTopDown)
        -- registerScriptHandler functions must be before the reloadData function 先要注册 才能使用reloadData
        self.tableView:registerScriptHandler(handler(self, self.scrollViewDidScroll),CCTableView.kTableViewScroll)       --滚动时的事件
        self.tableView:registerScriptHandler(handler(self, self.scrollViewDidZoom),CCTableView.kTableViewZoom)           
        self.tableView:registerScriptHandler(handler(self, self.tableCellTouched),CCTableView.kTableCellTouched)         --触碰到Cell的事件
        self.tableView:registerScriptHandler(handler(self, self.tableCellAtIndex),CCTableView.kTableCellSizeAtIndex)     --Cell的内容
        self.tableView:registerScriptHandler(handler(self, self.cellSizeForTable),CCTableView.kTableCellSizeForIndex)    --Cell的尺寸
        self.tableView:registerScriptHandler(handler(self, self.numberOfCellsInTableView),CCTableView.kNumberOfCellsInTableView)   --Cell的行数

        self.userChatBox:addChild(self.tableView,2) 

        --
    end

end


function ChatLayer:_readCcbi()
    
    readCCbiObject(self,"mCloseBtn","CCSprite")   
    readCCbiObject(self,"sysAndUserChatBox", "CCNode")
    readCCbiObject(self,"userChatBox", "CCNode")
    readCCbiObject(self,"editBoxBar","CCScale9Sprite")
    readCCbiObject(self,"editBoxBtn","CCScale9Sprite",{WordManager:getWord("ChatLayer_005"), text.color1, text.color20, 28})
    readCCbiObject(self,"popNode", "CCNode")
    for i=1,4 do
        readCCbiObject(self,"button_"..i,"CCSprite",{WordManager:getWord("ChatLayerTitle_00"..i+1), text.color1, text.color20, 30})   
    end
  
end

function ChatLayer:_initListener()

    if self._needInitListener then
        self._needInitListener = false

        self:setTouchEnabled(true)

        self.mCloseBtn:setTouchEnabled(true)
        self.mCloseBtn:addNodeEventListener(cc.NODE_TOUCH_EVENT, handler(self, self.onCloseBtn))


        self.editBoxBtn:setTouchEnabled(true)
        self.editBoxBtn:addNodeEventListener(cc.NODE_TOUCH_EVENT, 
            function(event) 
                return touchEvent(self.editBoxBtn, event, handler(self, self.onEditBoxBtn)) 
            end)


        for i=1, 4 do
            self["button_" .. i]:setTouchEnabled(true)
            self["button_"..i]:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event) return self:onTopBtnTouch(event,i) end) 
        end
    end

end

function ChatLayer:onCloseBtn(event)

    if event.name == "began" then
        self.mCloseBtn:setFlipY(true)
        return true
    elseif event.name == "ended" then
        SoundManager:playMainSceneSound("button")
        self.mCloseBtn:setFlipY(false)
        self:removeFromParent()
    end

end

function ChatLayer:onEditBoxBtn()

    local text = string.trim(self.editBox:getText())

    if text ~= "" then 
        self.editBox:setText("")
        local cdata = {to_uid = self._displayingPersonUid or self._displayingChatType, msg = filterMessage(text)}
        local chatItem = ChatSystem:parseChatItem(nil,cdata)
        ChatSystem:sendChat(chatItem)   --发送msg

        self:_updateChatContentBoxWithData()
    end

end

function ChatLayer:onTopBtnTouch(event, targetChatType)

    if event.name == "began" then
        if targetChatType ~= self._displayingChatType then
            return true
        end
    elseif event.name == "ended" then
        SoundManager:playMainSceneSound("button")

        if  DataSystem.unionBaseData.myUnionInfo == nil and targetChatType == ENUM_CHAT_TYPE.union then
            AlertManager:showTextLabelAlert(WordManager:getWord("ChatLayer_015"));
        else   
            self:_updateTopBtnDisplay(targetChatType)
            self._displayingChatType = targetChatType 
            self._displayingChatList = ChatSystem:getChatListByType(self._displayingChatType)  
            self._displayingLabelHeightList = ChatSystem:getChatLableHeightLists(self._displayingChatType) 
            self:_updateChatContentBoxWithData()
        end
    end

end

function ChatLayer:_updateTopBtnDisplay(targetChatType)

    for i=1, 4 do
        if targetChatType == i then
            self["button_" .. i]:setDisplayFrame(CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("button_69.png"))
        else
            self["button_" .. i]:setDisplayFrame(CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("button_70.png"))
        end
    end
end



function ChatLayer:_updateChatContentBoxWithData()
  
    -----
    self:updateTopLabel()

    self:fixTableviewRect()
    self:refreshTable()
    self:_updateTableViewTouchState()

end

function ChatLayer:updateTopLabel()   --self.topRichLable_realHeight update    需要随即调用 fixTableviewRect 修改tableview size
    
    if self.sysAndUserChatBox:getChildByTag(topChatNodeTag) then
        self.sysAndUserChatBox:removeChildByTag(topChatNodeTag)
    end

    local chatItem = ChatSystem.latestSystemChatItem
    self._topSysChatLableHeight = ChatSystem:getChatHeight(chatItem) --RichLabel_getHeight(top_heightParam)
    --print("test mess", self._topSysChatLableHeight)
    --top rend
    local htmlText = "<font size=\"25\" color=\"#E78651\">".."【".."</font><font size=\"25\" color=\"#DBC651\">"..chatItem.src_nick.."<font size=\"25\" color=\"#E78651\">".."】".."</font></font><font size=\"25\" color=\"#B762C0\">"..chatItem.msg.."</font>"
    local topLabel = getRichText(htmlText, ChatSystem.sysChatWidth)     --.....

    topLabel:setPosition(( display.size.width-ChatSystem.sysChatWidth)*0.5,self.sysAndUserChatBox:getContentSize().height- 30- 5)   -- 富文本的载体 node 在整个富文本中心  位置有点怪 20号减28 25号减30
    topLabel:addTo(self.sysAndUserChatBox,1,topChatNodeTag)

end

function ChatLayer:fixTableviewRect()
   
    self.tableviewHeight = self.userChatBox:getContentSize().height-self._topSysChatLableHeight-5
    self.tableView:setViewSize(CCSizeMake(self.userChatBox:getContentSize().width, self.tableviewHeight))
    self.tableView:setPosition(CCPointMake(self.userChatBox:getPositionX(),self.userChatBox:getPositionY()))
   
end


function ChatLayer:_updateTableViewTouchState()  

    if self.tableViewTouchEnableList[self._displayingChatType] then
        self:_updateTableViewTouchEnableList(true) 
    else
        local cellAtIndex0 = self.tableView:cellAtIndex(0)
        local cellAtIndex0IsNotTop = cellAtIndex0 and cellAtIndex0:getPositionY() + self:cellSizeForTable(self.tableView, 0) < self.tableviewHeight 
        self:_updateTableViewTouchEnableList(not(cellAtIndex0IsNotTop) and table.nums(self._displayingChatList) > 0)
    end
   
end

function ChatLayer:_updateTableViewTouchEnableList(isTouchEnable)

    self.tableViewTouchEnableList[self._displayingChatType] = isTouchEnable
    self.tableView:setTouchEnabled(isTouchEnable)

end
------------------------------------------
function ChatLayer:refreshTable(scrollOffsetY)

    self.listNums = table.nums(self._displayingChatList)   

    self.tableView:reloadData()  

    local tScrollOffsetY = self._scrollOffsetYs[self._displayingChatType] or scrollOffsetY
    if tScrollOffsetY then
       self.tableView:setContentOffset(CCPoint(0, tScrollOffsetY),false)  
    end
end

function ChatLayer:tableCellAtIndex(t, idx) 

    local idx  = idx + 1 
    local cell = t:dequeueCell()   --得到Cell 

    local data =  self._displayingChatList[idx]
    data.idx =  idx
    local item = nil

    if nil == cell then  
        cell          = CCTableViewCell:new()
        item          = require("app.scenes.main.layers.chat.ChatItem").new(self);
        self:refeshItem(item,data)
        cell:addChild(item,10,100010)
    else
        item = cell:getChildByTag(100010)
        if item.itemType ~= self.currentTabType then
            item:resetItem()
        end
        self:refeshItem(item,data)
    end

    return cell
end

function ChatLayer:refeshItem(item,data) 
    
    if self._displayingChatType == ENUM_CHAT_TYPE.total  then
        item:refreshItem(data)
    elseif self._displayingChatType == ENUM_CHAT_TYPE.world  then
        item:refreshItem(data)
    elseif self._displayingChatType == ENUM_CHAT_TYPE.union  then
        item:refreshItem(data)
    elseif self._displayingChatType == ENUM_CHAT_TYPE.team  then
        item:refreshItem(data)
    elseif self._displayingChatType == ENUM_CHAT_TYPE.person  then
        item:refreshItem(data)
    end

end

function ChatLayer:scrollViewDidScroll(view)

    local viewOffsetY = view:getContentOffset().y

    if  self.fScrollPreY == nil then  self.fScrollPreY = viewOffsetY  end
    local offsetY   = self.fScrollPreY - viewOffsetY
    if offsetY~=0 then self.isScroll = true end

    self.fScrollPreY = viewOffsetY

end
function ChatLayer:scrollViewDidZoom(view)end
function ChatLayer:tableCellTouched(table,cell)
    self.isScroll = false
end

function ChatLayer:cellSizeForTable(table, idx)  --reload之后就会计算出所有cellsize 并不只是显示的cell

    local height 
    if self._displayingChatList[idx+1].src_uid == ChatSystem.sysUid then
        height = self._displayingLabelHeightList[idx+1][1]+5
    else
        height = self._displayingLabelHeightList[idx+1][1]+5 + 85
    end

    return height ,0

end

function ChatLayer:numberOfCellsInTableView(t)
   return self.listNums
end


---------------
function ChatLayer:_onEditBox(event, editbox)

    if event == "began" then
        print("开始输入")
    elseif event == "changed" then
        print("输入框内容发生变化")
    elseif event == "ended" then
        print("输入结束")
    elseif event == "return" then
        print("从输入框返回")
    end

end

function ChatLayer:onReceiveNewChat(chatItem)
   
    if chatItem.chatType == self._displayingChatType then
        
        self:_updateChatContentBoxWithData()



    else -- 小红点？
    end


end

return ChatLayer

